﻿using System;
using System.Drawing;
using System.IO;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;
using Image = System.Web.UI.WebControls.Image;

namespace Library.WebControls.SimpleGridView {
	public class SpGridViewDesign : ControlDesigner {
		public override string GetDesignTimeHtml() {
			var sw = new StringWriter();
			var tw = new HtmlTextWriter(sw);
			var grid = (SpGridView)Component;
			grid.CreateCssLink().RenderControl(tw);
			var divGrid = new SpDivGridView();
			divGrid.GridView = grid;
			divGrid.TableGrid.Rows.Add(CreateHeaderRow(grid));
			for (int i = 1; i <= 5; i++) {
				divGrid.TableGrid.Rows.Add(CreateEmptyContain(grid));
			}
			divGrid.Style[HtmlTextWriterStyle.Width] = grid.Width.ToString();
			divGrid.RenderMeWithoutChildGrid(tw);
			return sw.ToString();
		}


		protected virtual TableRow CreateHeaderRow(SpGridView gridView) {
			var headerRow = new TableRow {
				CssClass = gridView.EnableSort ? "spgvSortHeaderRow" : "spgvHeaderRow"
			};

			for (int i = 0; i < gridView.VisibleColumns.Count; i++) {
				var column = gridView.VisibleColumns[i];
				var headerCell = new TableCell { CssClass = i > 0 ? "spgvCell" : "spgvFirstCell" };
				if (column.HeaderTemplate != null) {
					column.HeaderTemplate.InstantiateIn(headerCell);
				} else {
					headerCell.Controls.Add(new LiteralControl(column.Caption));
				}
				column.HeaderStyle.CopyStyleToCell(headerCell);
				headerRow.Cells.Add(headerCell);
			}

			if (gridView.HasChildGrid) {
				headerRow.Cells[0].CssClass = "spgvCell";
				var firsCell = new TableCell { CssClass = "spgvFirstCell" };
				headerRow.Cells.AddAt(0, firsCell);
			}

			return headerRow;
		}

		private static TableRow CreateEmptyContain(SpGridView gridView) {
			var contentRow = new TableRow {
				CssClass = "spgvRow"
			};

			for (int i = 0; i < gridView.VisibleColumns.Count; i++) {
				var column = gridView.VisibleColumns[i];
				var cell = new TableCell();
				if (i > 0 || gridView.HasChildGrid)
					cell.CssClass = "spgvCell";
				else {
					cell.CssClass = "spgvFirstCell";
				}

				column.ContentStyle.CopyStyleToCell(cell);
				contentRow.Cells.Add(cell);
				cell.Controls.Add(new LiteralControl(String.Format("{0} Text", column.Caption)));

			}

			if (gridView.HasChildGrid) {
				var firstCell = new TableCell {
					CssClass = "spgvFirstCell",
					HorizontalAlign = HorizontalAlign.Center,
					VerticalAlign = VerticalAlign.Middle
				};
				var image = new Image { ImageUrl = gridView.CollapseImagePath };

				firstCell.Controls.Add(image);
				contentRow.Cells.AddAt(0, firstCell);

			}

			return contentRow;
		}
	}
}
